package com.bykj.property.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bykj.property.controller.vo.export.PaymentRecordExport;
import com.bykj.property.model.*;
import com.bykj.property.service.*;
import com.bykj.property.config.common.exception.CustomException;
import com.bykj.property.controller.vo.response.ErrorCode;
import com.bykj.property.controller.vo.response.RespResult;
import com.bykj.property.controller.vo.request.PendingPaymentRecordPageRequest;
import com.bykj.property.controller.vo.export.PendingPaymentRecordExport;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.bykj.property.util.ExcelUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.BindingResult;

import javax.validation.ValidationException;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.alibaba.fastjson.JSON;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.sql.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import javax.validation.constraints.NotEmpty;

    import org.springframework.web.bind.annotation.RestController;

/**
* <p>
    * 待缴费记录表 前端控制器
    * </p>
*
* @author liangyiming
* @since 2019-06-20
*/

@Slf4j
    @Api(tags = {"待缴费记录表"})
    @RestController
   @RequestMapping("/admin/PendingPaymentRecord")
        public class PendingPaymentRecordController {
    @Autowired
    PendingPaymentRecordService targetService;
    @Autowired
    PmVillageService pmVillageService;
    @Autowired
    PmUnitService pmUnitService;
    @Autowired
    PmProprietorService pmProprietorService;
    @Autowired
    ChargeTypeService chargeTypeService;

    @ApiOperation(value="添加")
    @RequestMapping(value = "/add",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    public RespResult add(PendingPaymentRecord model, BindingResult bindingResult) {
    return RespResult.ok(targetService.save(model));
    }

    @ApiOperation(value="更新")
    @RequestMapping(value = "/update",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    public RespResult update(PendingPaymentRecord model) {
    return RespResult.ok(targetService.updateById(model));
    }

    @ApiOperation(value="删除接口")
    @RequestMapping(value = "/delete",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    public RespResult delete(@NotEmpty String id) {
    return RespResult.ok(targetService.removeById(id));
    }

    @ApiOperation(value="查询列表接口")
    @RequestMapping(value = "/query",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    public RespResult query(PendingPaymentRecordPageRequest pageRequest, BindingResult bindingResult) {
    if(pageRequest.getSize()==-1){
    return RespResult.ok(targetService.list());
    }
    return RespResult.ok(targetService.queryPage(pageRequest));
    }

    @ApiOperation(value="查询详情接口")
    @ApiImplicitParams({
    @ApiImplicitParam(name="id",value="id",dataType="String", paramType = "query")
    })
    @RequestMapping(value = "/get",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    public RespResult get(@NotEmpty String id) {
    return RespResult.ok(targetService.getById(id));
    }
    @RequestMapping(value = "/createPending",method = RequestMethod.POST,produces = "application/json;charset=UTF-8",consumes ="application/json;charset=UTF-8" )
    public RespResult createPending(@RequestParam("pmVillageId") Long pmVillageId, @RequestParam("chargeTypeId")Long chargeTypeId, BigDecimal price, @RequestParam(value = "datarange[]") String[] datarange){
        String startStr = datarange[0].replace("Z", " UTC");
        String endStr = datarange[1].replace("Z", " UTC");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");

        try {
            Date start = new Date(format.parse(startStr).getTime());
            Date end = new Date(format.parse(endStr).getTime());
            targetService.createPendingPaymentRecord(pmVillageId,chargeTypeId,price,start,end);
        }catch (Exception e){
          e.printStackTrace();
        }




        //targetService.createPendingPaymentRecord(pmVillageId,chargeStandardId);
           return RespResult.ok();
    }
    // 导出操作
    @ApiOperation(value="导出excel表格")
    @RequestMapping("/exportExcel")
    public void export(PendingPaymentRecordPageRequest pageRequest,HttpServletResponse response) {
    List<PendingPaymentRecord> list =null;

    QueryWrapper queryWrapper=new QueryWrapper();
    if(!StringUtils.isEmpty(pageRequest.getDoorNumber())){
        queryWrapper.like("door_number",pageRequest.getDoorNumber());
    }
        if(!StringUtils.isEmpty(pageRequest.getPropName())){
            queryWrapper.like("prop_name",pageRequest.getPropName());
        }


    if(pageRequest.getSize()==-1){
    list=targetService.list(queryWrapper);
    }else{

    list=targetService.page(pageRequest,queryWrapper).getRecords();
    }

    // 模拟从数据库获取需要导出的数据
        List<PendingPaymentRecordExport> listExport = new ArrayList<>();
        list.forEach(m->{PendingPaymentRecordExport exp=JSON.parseObject(JSON.toJSONString(m),PendingPaymentRecordExport.class);
           ChargeType chargeType= chargeTypeService.getById(m.getChargeTypeId());
           if(chargeType!=null) {
               exp.setChargeName(chargeType.getChargeName());
           }

            PmVillage pmVillage= pmVillageService.getById(m.getPmVillageId());
            if(pmVillage!=null) {
                exp.setViName(pmVillage.getViName());
            }
            PmUnit pmUnit=pmUnitService.getById(m.getPmUnitId());
            if(pmUnit!=null) {
                exp.setUnName(pmUnit.getUnName());
            }
            PmProprietor   pmProprietor =pmProprietorService.getById(m.getPmProprietorId());
        if(pmProprietor!=null) {
            exp.setPropName(pmProprietor.getPropName());
        }


        listExport.add(exp);});
    // 导出操作
    ExcelUtils.exportExcel(listExport, "待缴费记录表", "PendingPaymentRecord", PendingPaymentRecordExport.class, "PendingPaymentRecord2019-06-20.xls", response);

    }
    @ApiOperation(value="导入excel表格")
    @PostMapping("/importExcel")
    public String importExcel2(@RequestParam("file") MultipartFile file) {
    ImportParams importParams = new ImportParams();
    // 数据处理
    importParams.setHeadRows(1);
    importParams.setTitleRows(1);
    // 需要验证
    importParams.setNeedVerfiy(false);

    try {
    ExcelImportResult<PendingPaymentRecordExport> result = ExcelImportUtil.importExcelMore(file.getInputStream(), PendingPaymentRecordExport.class,
        importParams);
        List<PendingPaymentRecordExport> list = result.getList();
            for (PendingPaymentRecordExport model : list) {

            log.info("从Excel导入数据到数据库的详细为 ：{}", JSON.toJSONString(model));
            //TODO 将导入的数据做保存数据库操作
            }
            log.info("从Excel导入数据一共 {} 行 ", list.size());
            } catch (IOException e) {
            log.error("导入失败：{}", e.getMessage());
            } catch (Exception e1) {
            log.error("导入失败：{}", e1.getMessage());
            }
            return "导入成功";
            }

                }
